#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>


#include <dirent.h> // DIR dirent

#include <stdarg.h>   // va_list


#ifdef _WIN32
    #define PATH_SEPARATOR "\\"
#else
    #define PATH_SEPARATOR "/"
#endif

#define DELETE_TMPFILE "00010"

void splicString(char *dst, int len, int argc, ...);


void File_Remove(const char *path, const char *file);

void Dir_Remove(const char *path);



int main(int argc, char *argv[]) {
    printf("%s\n", argv[0]);

    if(argc == 1){
        return 0;
    } else {

        Dir_Remove(argv[1]);
    }

    return 0;
}

void Dir_Remove(const char *path){
    DIR *root_path =  opendir(path);
    struct dirent *de;

    char file_path[256];
    memset(file_path, 0, sizeof(file_path));

    while ((de = readdir(root_path)) != NULL) {

        memset(file_path,0, sizeof(char));

        if( strcmp(de->d_name, ".") && strcmp(de->d_name, "..")){

            if(de->d_type == 8){
                File_Remove(path, de->d_name);
            }

            if( de->d_type == 4){

                splicString(file_path, sizeof(file_path),
                        3, path, PATH_SEPARATOR, de->d_name);

                Dir_Remove(file_path);
            }

        }

    }
    closedir(root_path);

    rmdir(path);

}


void File_Remove(const char *path, const char *file){

    int flag = 0;

    char old_path[256];
    char new_path[256];
    memset(old_path, 0 ,sizeof(old_path));
    memset(new_path, 0 ,sizeof(new_path));

    splicString(old_path, sizeof(old_path), 3, path, PATH_SEPARATOR, file);

    splicString(new_path, sizeof(new_path), 3, path, PATH_SEPARATOR, DELETE_TMPFILE);

    FILE *pHandle = fopen(old_path, "w");
    //printf("%s\n", new_path);

    if(pHandle){
        flag = 1;
        char *buf = "2222";
        fwrite(buf, sizeof(char),strlen(buf) ,pHandle);
        fclose(pHandle);

        rename(old_path, new_path);
        int rv = remove(new_path);

        printf("%d: ", rv);
    }

    printf("%s\n", old_path);

}


void splicString(char *dst, int len, int argc, ...){
    memset(dst,0, len);
    va_list args;
    va_start(args, argc);
    char *next = 0;
    for(int i =0; i< argc; ++i){
        next = va_arg(args, char*);
        strcat(dst, next);
    }
    va_end(args);
}


